
package com.trial.area.coupon.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.trial.area.common.controller.BaseController;
import com.trial.area.common.param.SessionUserInfo;
import com.trial.area.common.utils.ExcelUtil;
import com.trial.area.coupon.entity.CouponVO;
import com.trial.area.coupon.param.CouponParam;
import com.trial.area.coupon.service.CouponService;
import com.trial.area.goods.entity.GoodsVO;
import com.trial.area.goods.param.GoodsParam;
import com.trial.area.goods.service.GoodsService;

/**
 * 优惠券Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class CouponController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(CouponController.class);

    @Autowired
    private CouponService couponService;

    @Autowired
    private GoodsService goodsService;

    private final static String ADMIN_LIST_PAGE = "/admin/coupon/coupon_list";

    private final static String ADMIN_CREATE_PAGE = "/admin/coupon/coupon_create";
    
    private final static String LIST_PAGE = "/html5/coupon/coupon_list_ajax";

    private final static String TO_EXCHANGE_PAGE = "/html5/coupon/coupon_exchange";
    
    @RequestMapping(value = "/admin/coupon/toCreate")
    public ModelAndView intoCreate() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        CouponVO couponVO = new CouponVO();
        couponVO.setApplicationScope(1);
        couponVO.setExtraFee(new BigDecimal(0));
        resultMap.put("couponVO", couponVO);
        return new ModelAndView(ADMIN_CREATE_PAGE, resultMap);
    }
    
    /**
     * 批量生成券码
     *
     * @param couponName 券码名称
     * @param couponBatch 批次号
     * @param acquiringWay 获取途径说明
     * @param couponNum 生成的数量
     * @param couponPre 券码前缀
     * @return
     */
    @RequestMapping(value = "/admin/coupon/create", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String create(String couponName, String couponBatch, String acquiringWay, Integer couponNum, String couponPre, Integer applicationScope,
        String applicationGoodsName, BigDecimal extraFee) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        try {
            if (StringUtils.isBlank(couponName)) {
                resultMap.put("result", false);
                resultMap.put("message", "券码名称不能为空");
                return JSONObject.toJSONString(resultMap);
            }
            
            if (StringUtils.isBlank(couponBatch)) {
                resultMap.put("result", false);
                resultMap.put("message", "批次号不能为空");
                return JSONObject.toJSONString(resultMap);
            }
            
            if (StringUtils.isBlank(couponPre)) {
                resultMap.put("result", false);
                resultMap.put("message", "券码编号前缀不能为空");
                return JSONObject.toJSONString(resultMap);
            }
            
            if (couponPre.length() != 2) {
                resultMap.put("result", false);
                resultMap.put("message", "券码编号前缀应为2位大写字母");
                return JSONObject.toJSONString(resultMap);
            }
            
            if (couponNum <= 0 || couponNum > 5000) {
                resultMap.put("result", false);
                resultMap.put("message", "一次生成的券码数量应在1到5000条");
                return JSONObject.toJSONString(resultMap);
            }
            String applicationGoods = "";
            if (applicationScope != null && applicationScope == 2) {
                if (StringUtils.isBlank(applicationGoodsName)) {
                    resultMap.put("result", false);
                    resultMap.put("message", "单品类券码，必须填写适用商品名称");
                    return JSONObject.toJSONString(resultMap);
                }
                
                GoodsParam goodsParam = new GoodsParam();
                goodsParam.setGoodsName(applicationGoodsName);
                List<GoodsVO> goodsList = goodsService.queryByPage(goodsParam);
                
                if (goodsList != null && goodsList.size() == 1) {
                    applicationGoods = goodsList.get(0).getGoodsId();
                } else if (goodsList == null || goodsList.size() == 0) {
                    resultMap.put("result", false);
                    resultMap.put("message", "单品类券码，根据商品名称：" + applicationGoodsName + "未找到商品");
                    return JSONObject.toJSONString(resultMap);
                } else if (goodsList.size() > 1) {
                    resultMap.put("result", false);
                    resultMap.put("message", "单品类券码，根据商品名称：" + applicationGoodsName + "找到多个商品商品");
                    return JSONObject.toJSONString(resultMap);
                }
            } else if (applicationScope != null && applicationScope > 2) {
                resultMap.put("result", false);
                resultMap.put("message", "无法识别的券码类型");
                return JSONObject.toJSONString(resultMap);
            }
            
            // 验证券码名称和批次号唯一
            CouponParam couponParam = new CouponParam();
            couponParam.setCouponName(couponName);
            couponParam.setCouponBatch(couponBatch);
            List<CouponVO> dataList = couponService.queryByPage(couponParam);
            
            if (dataList != null && dataList.size() > 0) {
                resultMap.put("result", false);
                resultMap.put("message", "已存在券码为：" + couponName + " 并且批次号为：" + couponBatch + " 的券码，请使用其他名称或批次号！");
                return JSONObject.toJSONString(resultMap);
            }
            
            Integer insertNum = couponService.batchCreate(couponName, couponBatch, acquiringWay, couponNum, couponPre, applicationScope,
                applicationGoodsName, applicationGoods, extraFee);
                
            resultMap.put("result", true);
            resultMap.put("message", "成功生成" + insertNum + "条券码");
            return JSONObject.toJSONString(resultMap);
        } catch (Exception e) {
            logger.error("券码批量生成出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "券码批量生成出错：" + e.getLocalizedMessage());
            return JSONObject.toJSONString(resultMap);
        }
    }

    /**
     * 根据条件导出券码
     *
     * @param couponParam
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/admin/coupon/export")
    public ModelAndView export(String couponName, String couponBatch) {
        String fileName = "券码列表";
        // 填充projects数据
        
        CouponParam couponParam = new CouponParam();
        couponParam.setPageSize(Integer.MAX_VALUE);
        couponParam.setCouponName(couponName);
        couponParam.setCouponBatch(couponBatch);
        
        List<Map<String, Object>> couponlist = couponService.queryMapByPage(couponParam);
        String columnNames[] = { "券码名称", "券码批次号", "券码" };// 列名
        String keys[] = { "coupon_name", "coupon_batch", "coupon_no" };// map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            String exportName = couponName;
            if (couponlist != null && couponlist.size() > 0) {
                Integer applicationScope = couponlist.get(0).get("application_scope") == null ? 1
                    : Integer.valueOf(couponlist.get(0).get("application_scope").toString());
                String applicationGoodsName = couponlist.get(0).get("application_goods_name") == null ? ""
                    : couponlist.get(0).get("application_goods_name").toString();
                if (applicationScope == 1) {
                    exportName = exportName + "_全品类";
                } else if (applicationScope == 1) {
                    exportName = exportName + "_" + applicationGoodsName;
                }
            }
            ExcelUtil.createWorkBook(exportName, couponlist, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);

        ServletOutputStream out = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));

            out = response.getOutputStream();
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            logger.error("券码导出Excel出错", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    logger.error("券码导出Excel出错", e);
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    logger.error("券码导出Excel出错", e);
                }
            }
        }
        return null;
    }
    
    @RequestMapping(value = "/admin/coupon/list")
    public ModelAndView queryAdminList(CouponParam couponParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> dataList = couponService.queryBatchByPage(couponParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", couponParam);
        return new ModelAndView(ADMIN_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/coupon/toExchange")
    public ModelAndView toExchange() {
        return new ModelAndView(TO_EXCHANGE_PAGE);
    }
    
    @RequestMapping(value = "/check/coupon/doExchange", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(String couponNo) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            couponNo = StringUtils.trim(couponNo);

            CouponVO couponVO = couponService.findByCouponNo(couponNo);
            
            if (couponVO == null) {
                resultMap.put("result", false);
                resultMap.put("message", "券码不存在");
                return JSONObject.toJSONString(resultMap);
            } else if (couponVO.getCouponState() != 1) {
                if (StringUtils.equals(seUser.getUserId(), couponVO.getUserId()) && couponVO.getCouponState() == 2) {
                    resultMap.put("result", true);
                    resultMap.put("subscribe", seUser.getSubscribe());
                    
                    String goodsMsg = "";
                    String goodsUrl = "";
                    if (couponVO.getApplicationScope() == 1) {
                        goodsMsg = "礼券类型：全品";
                        goodsUrl = getPath() + "/index";
                    } else if (couponVO.getApplicationScope() == 2) {
                        goodsMsg = "礼券类型：单品-" + couponVO.getApplicationGoodsName();
                        goodsUrl = getPath() + "/uncheck/goods/view/" + couponVO.getApplicationGoods();
                    }
                    
                    resultMap.put("goodsMsg", goodsMsg);
                    resultMap.put("goodsUrl", goodsUrl);
                    
                    resultMap.put("message", "兑换优惠券成功");

                    return JSONObject.toJSONString(resultMap);
                } else {
                    resultMap.put("result", false);
                    resultMap.put("message", "券码已兑换");
                    return JSONObject.toJSONString(resultMap);
                }
            } else {
                couponVO.setCouponState(2);
                couponVO.setUserId(seUser.getUserId());
                couponVO.setExpirationTime(DateTime.now().plusMonths(12).toDate());
            }
            
            Integer insertCount = couponService.update(couponVO);
            if (insertCount != null && insertCount == 1) {
                resultMap.put("result", true);
                resultMap.put("subscribe", seUser.getSubscribe());
                
                String goodsMsg = "";
                String goodsUrl = "";
                if (couponVO.getApplicationScope() == 1) {
                    goodsMsg = "礼券类型：全品";
                    goodsUrl = getPath() + "/index";
                } else if (couponVO.getApplicationScope() == 2) {
                    goodsMsg = "礼券类型：单品-" + couponVO.getApplicationGoodsName();
                    goodsUrl = getPath() + "/uncheck/goods/view/" + couponVO.getApplicationGoods();
                }
                
                resultMap.put("goodsMsg", goodsMsg);
                resultMap.put("goodsUrl", goodsUrl);
                
                resultMap.put("message", "兑换优惠券成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "兑换优惠券失败");
            }
        } catch (Exception e) {
            logger.error("兑换优惠券出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "兑换优惠券出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/check/coupon/list")
    public ModelAndView queryList(CouponParam couponParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");

        couponParam.setUserId(seUser.getUserId());
        List<CouponVO> dataList = couponService.queryByPage(couponParam);
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", couponParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }

}
